//
//  GTChannelViewController.m
//  GiftTalk
//
//  Created by Wan on 16/3/23.
//  Copyright © 2016年 Wan. All rights reserved.
//

#import "GTChannelViewController.h"
#import <AFNetworking.h>
#import "GTChannelViewCell.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import "GTGiftItem.h"
#import "GTSearchGiftHeader.h"
#import "GTGuideDetailViewController.h"

static NSString * const cellId = @"item";

@interface GTChannelViewController () <UITableViewDelegate>
@property (strong, nonatomic) AFHTTPSessionManager *manager;

/** 下一页url */
@property (strong, nonatomic) NSString *nextPageURLString;
/** 商品条目 */
@property (strong, nonatomic) NSMutableArray *giftItems;

/** 礼物数据 */
//@property (nonatomic,strong) NSMutableArray *giftItems;
@end

@implementation GTChannelViewController

#pragma mark 懒加载
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSMutableArray *)giftItems
{
    if (!_giftItems) {
        _giftItems = [NSMutableArray array];
    }
    return _giftItems;
}

#pragma mark 初始化
- (instancetype)initWithStyle:(UITableViewStyle)style
{
    GTChannelViewController *channelVc = [super initWithStyle:UITableViewStylePlain];
    channelVc.cellBackgroundColor = [UIColor clearColor];
    
    return channelVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化 tableView
    [self setupTableView];
    
    // 添加刷新控件
    [self setupRefresh];
}


- (void)setupTableView
{
    /** 设置内边距,为了解决 contentView 不被顶部标题栏和底部按钮遮挡住,穿透效果 */
    self.tableView.rowHeight = 150.0;
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat insetBottom = self.tableView.rowHeight - bottom + 8.0;
//    GTLog(@"底部距离：%f",insetBottom);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, insetBottom, 0);
    
    // *设置 tableView 滚动条的内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    // 去分割线 & 背景色
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    // 注册 cell
//    [self.tableView dequeueReusableCellWithIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([GTChannelViewCell class]) bundle:nil] forCellReuseIdentifier:cellId];
    
}

- (void)setupRefresh
{
    self.tableView.mj_header = [GTSearchGiftHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

    // 自动改变透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    // 进入刷新在状态
    [self.tableView.mj_header beginRefreshing];
//    self.tableView.mj_footer.hidden = YES;
}

- (void)chckFooterState
{
    if (self.nextPageURLString == nil) { // 全部数据加载完毕
//        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
        // 自动根据有无数据来显示和隐藏（有数据就显示，没有数据隐藏。默认是NO）
        self.tableView.mj_footer.automaticallyHidden = YES;
    } else { // 还没加载完毕
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark 加载数据
- (void)loadNewData
{
    if (!self.firstPageURLString) {
        [self.tableView.mj_header endRefreshing];
        return;
    }

    [self.manager GET:self.firstPageURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 字典数组 -> 模型数组
        NSArray *giftItems = [GTGiftItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"][self.dataArrayName]];

        // 删除所有旧数据
        [self.giftItems removeAllObjects];
        
        // 添加数据到缓存数组中
        [self.giftItems addObjectsFromArray:giftItems];
        
        // 下一页
        self.nextPageURLString = responseObject[@"data"][@"paging"][@"next_url"];
        
        // 刷新表格
        [self.tableView reloadData];
        
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        
        // 判断全部数据是否加载完毕
        [self chckFooterState];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        GTLog(@"%@", error);
    }];
}

- (void)loadMoreData
{
    if (!self.nextPageURLString) {
        [self chckFooterState];
        return;
    }
    
    [self.manager GET:self.nextPageURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSArray *giftItems = [GTGiftItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"][self.dataArrayName]];
        
        // 添加数据到缓存数组中
        [self.giftItems addObjectsFromArray:giftItems];
        
        NSString *nextUrlStr = responseObject[@"data"][@"paging"][@"next_url"];
        if ([nextUrlStr isKindOfClass:[NSNull class]] || [self.nextPageURLString isEqualToString:nextUrlStr]) {
            // 如果nextURLString是值为空的对象，就将self.nextPageURLString赋值为空对象
            // 注意nil和Null对象的区别，一个是空对象，一个是值为空的对象
            self.nextPageURLString = nil;
        } else {
            self.nextPageURLString = nextUrlStr;
        }
        
        // 底部控件刷新 结束处理
        [self chckFooterState];
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self chckFooterState];
        [self.tableView.mj_header endRefreshing];
        GTLog(@"%@",error);
    }];
}

- (void)dealloc
{
    [self.manager invalidateSessionCancelingTasks:YES];
}

#pragma mark - Table view data source
//
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
//    return 0;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    // 检测底部 footer 状态
    [self chckFooterState];
    
    return self.giftItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GTChannelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    cell.item = self.giftItems[indexPath.row];
    cell.backgroundColor = self.cellBackgroundColor;
    
    return cell;
}


#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GTLogFunc
    
    GTGiftItem *item = self.giftItems[indexPath.row];
    
    GTGuideDetailViewController *guidDetailVc = [[GTGuideDetailViewController alloc] init];
    guidDetailVc.ID = item.ID;
    
    [self.navigationController pushViewController:guidDetailVc animated:YES];
}

@end
